package com.yenroc.ho.aspect;

import com.yenroc.ho.resources.TkResourceProxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;

/**
 * @author： heyanpeng
 * @date： 2021/7/27
 */
@Aspect
@Component
public class GlobalDataSourceAspect {

    private final Logger log = LoggerFactory.getLogger(GlobalDataSourceAspect.class);

    @Autowired
    private TkResourceProxy tkResourceProxy;

    @Around("execution(* javax.sql.DataSource.getConnection(..))")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        try {
            Connection proceed = (Connection) proceedingJoinPoint.proceed();
            Connection connection = tkResourceProxy.proxyConnection(proceed);
            log.debug("Aspect proxy a sql connection: {}.", connection);
            return connection;
        } catch (Throwable throwable){
            log.error("Aspect getConnection error...", throwable);
        }
        return null;
    }
}
